package com.googlecode.perfectable.visuable.renderer.widget;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

import com.googlecode.perfectable.visuable.renderer.ElementRenderer;
import com.googlecode.perfectable.visuable.renderer.VisualRenderer;
import com.googlecode.perfectable.visuable.visual.Visual;

public class WidgetVisualRenderer implements VisualRenderer {
	private static final ObjectMapper MAPPER = new ObjectMapper();

	private final ArrayNode node;

	public WidgetVisualRenderer(ArrayNode node) {
		this.node = node;
	}

	@Override
	public ElementRenderer element(String elementName) {
		ObjectNode childNode = MAPPER.createObjectNode();
		checkNotNull(childNode);
		this.node.add(childNode);
		return new WidgetElementRenderer(childNode, elementName);
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
	}

	public static ObjectNode asNode(Visual visual) {
		ArrayNode node = MAPPER.createArrayNode();
		checkNotNull(node);
		try(VisualRenderer renderer = new WidgetVisualRenderer(node)) {
			visual.render(renderer);
		}
		checkState(node.size() == 1);
		JsonNode result = node.get(0);
		checkState(result instanceof ObjectNode);
		return (ObjectNode) result;
	}

}
